package cn.xuchunh.okhttpdemo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.xuchunh.okhttpdemo.toolbox.MyRequest;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    @Bind(R.id.request_get)
    Button btnRequestGet;

    @Bind(R.id.request_post)
    Button btnRequestPost;

    @Bind(R.id.edit_url)
    EditText etUrl;

    @Bind(R.id.result)
    TextView tvResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        btnRequestGet.setOnClickListener(this);
        btnRequestPost.setOnClickListener(this);

    }

    @Override
    protected void onDestroy() {
        VolleyHttpManager.getInstance(this).close();
        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        String url = etUrl.getEditableText().toString().trim();
        if (!TextUtils.isEmpty(url)) {
            int id = v.getId();
            if (id == R.id.request_get) {
                get(url);
            } else {
                post(url);
            }

        }
    }

    private void get(String url) {
        Map<String, String> headers = new HashMap<>();
        headers.put("charset", "UTF-8");
        headers.put("accept", "*/*");
        headers.put("connection", "Keep-Alive");
        HttpManager.getInstance().get(url, headers, new MyRequest.ResponseListener() {
            @Override
            public void onResponse(Response response) throws IOException {
                tvResult.setText(response.body().string());
            }

            @Override
            public void onFailure(Request request, IOException e) {

            }
        });
//        VolleyHttpManager.getInstance(this).get(url, new Listener<String>() {
//            @Override
//            public void onResponse(final String response) {
//                tvResult.setText(response.toString());
//            }
//        }, new ErrorListener() {
//            @Override
//            public void onErrorResponse(VolleyError error) {
//
//            }
//        });
    }

    private void post(String url) {
//        Map<String, String> headers = new HashMap<>();
//        headers.put("charset", "UTF-8");
//        headers.put("accept", "*/*");
//        headers.put("connection", "Keep-Alive");
//        headers.put("user-agent", "xuchunh");
//        RequestBody requestBody = new FormEncodingBuilder()
//                .add("param1", "value1")
//                .add("param2", "value2")
//                .build();
//        HttpManager.getInstance().post(url, headers, new MyCallback(), requestBody);
        Map<String, String> params = new HashMap<>();
        params.put("param1", "value1");
        params.put("param2", "value2");
        VolleyHttpManager.getInstance(this).post(url, new Listener<String>() {
            @Override
            public void onResponse(String response) {
                tvResult.setText(response.toString());
            }
        }, new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }, params);
    }

    public class MyCallback implements Callback {

        @Override
        public void onFailure(Request request, final IOException e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tvResult.setText(e.getMessage());
                }
            });
        }

        @Override
        public void onResponse(final Response response) throws IOException {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    String content = response.headers().toString() + "\n";
                    try {
                        content += response.body().string();
                    } catch (IOException e) {

                    }
                    tvResult.setText(content);
                }
            });
        }
    }

}
